﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Controllers;
using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.Extensions.DependencyInjection;

namespace Eqwww.Web
{
    public class AuthFilter : Attribute, IAuthorizationFilter
    {

        public void OnAuthorization(AuthorizationFilterContext context)
        {
            var descriptor = context?.ActionDescriptor as ControllerActionDescriptor;
            if (descriptor != null)
            {
                var actionName = descriptor.ActionName;
                var controllerName = descriptor.ControllerName;
                var areaName = descriptor.RouteValues.First(x => x.Key == "area").Value;
            }
            var authorizeApp = context.HttpContext.RequestServices.GetService<Eqwww.App.Authorize.AuthorizeApp>();
            var moduleId = context.HttpContext.Request.Cookies["EqwwwCurrentModuleId"];
            if(!authorizeApp.AuthorizeUrlAsync(moduleId, context.HttpContext.User, context.HttpContext.Request.Path).Result)
                context.Result = GetResult();
        }

        private IActionResult GetResult()
        {
            var result = new ViewResult();
            result.ViewName = "~/Views/Manage/PermissionAccessDenied.cshtml";
            return result;
        }
    }
}
